let express = require("express");
let app = express();
let http = require("http").Server(app); // 创建服务器
let io = require("socket.io")(http, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true,
  },
}); // 利用服务器初始化 socket.io
const appConfig = require("./app.config");

let cors = require("cors");
app.use(cors());

let bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const { initMock, mockList } = require("./mock/index");
const TIME_LAY = 1000;

function delayResponse(fn) {
  return (req, res) => {
    setTimeout(() => {
      fn && fn(req, res);
    }, TIME_LAY);
  };
}

mockList.forEach((item) => {
  let { url, method, response } = item;

  switch (method.toLowerCase()) {
    case "get":
      app.get(url, delayResponse(response));
      break;
    case "post":
      app.post(url, delayResponse(response));
      break;
    case "put":
      app.put(url, delayResponse(response));
      break;
    case "delete":
      app.delete(url, delayResponse(response));
      break;
    default:
      console.error(`Method ${method} is not supported.`);
  }
});

io.on("connection", function (socket) {
  console.log("a user connected");
  // 模拟axios方案的response方法里的参数
  const res = {
    json: (data) => socket.emit("message", data),
  };
  const req = {
    body: { params: null },
  };
  // 服务器主动发送消息到客户端（推送init和update初始化数据）
  socket.emit("message", initMock);
  socket.emit("message", initMock);
  // setTimeout(() => {
  //   socket.emit("message", initMock);
  // }, 5000);
  // 监听来自客户端的 send_message 事件
  socket.on("send_message", (msg) => {
    /* 这里处理下数据，让在mock文件通过axios格式写的接口格式在这里也能正常使用 */
    const msgObj = JSON.parse(msg);
    console.log("Received message:", msgObj);
    req.body.params = msgObj.params;
    const mockItem = mockList.find((item) => {
      return item.url.lastIndexOf(msgObj.methodName) > -1;
    });
    if (mockItem) {
      setTimeout(() => {
        mockItem.response && mockItem.response(req, res);
      }, TIME_LAY);
    }
    // 在这里你可以处理接收的消息，例如存储在数据库，或者发送给其他客户端等
  });
  socket.on("disconnect", function () {
    console.log("user disconnected");
  });
});

http.listen(appConfig.MOCK_PORT, () => {
  console.log(
    `Mock server is running at http://localhost:${appConfig.MOCK_PORT}`
  );
}); // 使用 http.listen 替换 app.listen
